<template>
  <a-modal
    title="新增人员"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item
              label="人员姓名"
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 16 }"
              has-feedback
              required
            >
              <a-input placeholder="请输入人员姓名" v-decorator="['userName', {rules: [{required: true, message: '请输入人员姓名！'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="人员单位"
              :loading="treeLoading"
              required
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 16 }"
              has-feedback
            >
              <a-cascader
                ref="orgTree"
                tree-node-filter-prop="title"
                :tree-check-strictly="true"
                :show-search="true"
                :show-all-levels="false"
                style="width: 100%"
                :dropdownStyle="{ maxHeight: 600, overflow: 'auto'}"
                placeholder="请选择人员单位"
                allow-clear
                has-feedback
                :options="unitTree"
                @change="handleOrganNameClick"
                treeCheckStrictly
                :rules="[{ required: true, message: '请选择人员单位'}]"
                :title="organizationName"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 16 }"
              label="手机号"
              required
            >
              <a-input
                placeholder="手机号"
                style="width: 100%"
                v-decorator="['mobile', , {required: true, message: '请输入手机号!'}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="身份证号"
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 16 }"
              has-feedback
            >
              <a-input placeholder="请输入身份证号" v-decorator="['idCard']"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="邮箱"
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 16 }"
              has-feedback
            >
              <a-input placeholder="请输入邮箱" v-decorator="['email']"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="员工编号"
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 16 }"
              has-feedback
              required
            >
              <a-input placeholder="请输入员工编号" required v-decorator="['employeeNo', {required: true, message: '请输入员工编号！'}]"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="性别" required :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
              <a-radio-group v-decorator="['userSex']">
                <a-radio value="1">男</a-radio>
                <a-radio value="2">女</a-radio>
                <a-radio value="0">未知</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { addUser, getUnitTree } from '@/api/modular/system/violationManage'
import { mapGetters } from 'vuex'
import { Cascader } from 'ant-design-vue'
  export default {
    components: {
      'a-cascader': Cascader
    },
    data () {
      return {
        visible: false,
        confirmLoading: false,
        unitTree: [],
        treeLoading: true,
        defaultExpandedKeys: [],
        organizationId: '',
        organizationName: '',
        replaceFields: {
          children: 'children',
          title: 'title',
          key: 'workflowId',
          value: 'id',
          parentId: 'parentId'
        },
        secondOraName: {
          id: ''
        },
        form: this.$form.createForm(this)
      }
    },
    created() {
      this.getUnitTree()
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    mounted() {
      this.setDisabledToParent(this.unitTree)
      // 找出所有拥有子节点的节点并标记为“disabled”
      this.unitTree.forEach((node) => {
        if (node.children) {
          this.disabledIds.push(node.organizationId)
          node.children.forEach((child) => {
            this.disabledIds.push(child.organizationId)
          })
        }
      })
    },
    methods: {
      add () {
        this.visible = true
      },
      setDisabledToParent(List) {
        List.forEach((item) => {
          if (item.children && item.children.length > 0) {
            // 递归遍历子节点
            this.setDisabledToParent(item.children)
            // 设置父节点的 disabled 属性
            item.disabled = true
          }
        })
        // console.log(List)
      },
        // 组织树
      getUnitTree () {
        this.secondOraName.id = this.userInfo.secondOrganizationName
        // console.log(this.secondOraName)
        getUnitTree(Object.assign(this.secondOraName)).then(res => {
          this.treeLoading = false
          this.unitTree = this.transformData(res.data)
        })
        this.visible = false
      },
      transformData(data) {
        function transform(data) {
          return data.map(item => ({
            id: item.id,
            label: item.title, // 将 title 转换为 label
            value: item.value,
            children: item.children ? transform(item.children) : []
          }))
        }
        return transform(data)
      },
      handleOrganNameClick(value, label, e) {
        if (value && label) {
          // 获取当前选择的单位的节点对象
          if (Array.isArray(label) && label.length > 0) {
            const selectedLabels = label.map(item => item.label)
            const selectedValues = value
            const lastSelectedLabel = selectedLabels[selectedLabels.length - 1]
            const lastSelectedValue = selectedValues[selectedValues.length - 1]
            this.organizationName = lastSelectedLabel // 将多个单位的标签用逗号分隔
            // console.log(this.organizationName)
            this.organizationId = lastSelectedValue // 将多个单位的值用逗号分隔
          }
        }
      },

      handleSubmit () {
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
          console.log(values)
          if (!errors) {
            values.organizationName = this.organizationName
            values.organizationId = this.organizationId
            if (values.organizationName !== undefined && values.organizationId !== undefined && values.userName !== undefined &&
            values.userSex !== undefined && values.employeeNo !== undefined && values.mobile !== undefined &&
            values.organizationName !== '' && values.organizationId !== '' &&
            values.userName !== '' && values.userSex !== '' && values.mobile !== '' && values.employeeNo !== '') {
              this.confirmLoading = true
              addUser(values).then((res) => {
                if (res.success) {
                  this.$message.success('新增人员成功')
                  this.visible = false
                  this.confirmLoading = false
                  this.$emit('ok')
                  this.form.resetFields()
                } else {
                  this.$message.error('新增人员失败：' + res.message)
                }
              }).finally((res) => {
                this.confirmLoading = false
              })
            } else {
              this.$message.warning('请完善信息！')
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.organizationName = ''
        this.organizationId = ''
      }
    }
  }
</script>
